"""
Time：   2025/8/24 12:45
"""
import collections
import datetime
import os
import shutil
import re
import subprocess


def copy_directory(src_dir, dst_dir):
    """
    Copy the directory and all its contents to the target directory.
    :param src_dir: Source directory path
    :param dst_dir: Destination directory path
    """
    if not os.path.exists(src_dir):
        raise FileNotFoundError(f"Source directory does not exist: {src_dir}")
    shutil.copytree(src_dir, dst_dir)


def replace_xx_path_in_lua(target_dir, new_path_value):
    """
    Replace the value after xx_path = in all .lua files under target_dir.
    :param target_dir: Directory to search for .lua files
    :param new_path_value: The value to replace after xx_path =
    """
    for root, _, files in os.walk(target_dir):
        for file in files:
            if file.endswith('.lua'):
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    lines = f.readlines()
                with open(file_path, 'w', encoding='utf-8') as f:
                    for line in lines:
                        if 'xx_path =' in line:
                            line = re.sub(r'(xx_path\s*=\s*).+', r'\1' + new_path_value, line)
                        f.write(line)


def delete_cache(target_dir, cache_dir_name=''):
    """
    Delete all cache directories named cache_dir_name under target_dir.
    :param target_dir: Directory to search for cache directories
    :param cache_dir_name: Name of the cache directories to delete
    """
    for root, dirs, _ in os.walk(target_dir):
        for dir_name in dirs:
            if dir_name == cache_dir_name:
                cache_dir_path = os.path.join(root, dir_name)
                shutil.rmtree(cache_dir_path)


def batch_copy_directory(demo_dir, parent_dir, count, new_path_value):
    """
    Batch copy the demo directory to the parent directory multiple times and replace xx_path in .lua files.
    :param demo_dir: Source demo directory path
    :param parent_dir: Destination parent directory path
    :param count: Number of copies to create
    :param new_path_value: The value to replace after xx_path =
    """
    if not os.path.exists(demo_dir):
        raise FileNotFoundError(f"Source demo directory does not exist: {demo_dir}")
    if not os.path.exists(parent_dir):
        os.makedirs(parent_dir)
    date_str = datetime.datetime.now().strftime('%Y_%m_%d')
    for i in range(1, count + 1):
        dst_dir = os.path.join(parent_dir, f"{date_str}_runcard_{i}")
        if os.path.exists(dst_dir):
            shutil.rmtree(dst_dir)
        shutil.copytree(demo_dir, dst_dir)
        replace_xx_path_in_lua(dst_dir, new_path_value)


def run_system_command(command):
    """
    Execute the given system command.
    :param command: Command string to execute
    :return: (output, return_code)
    """
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    return result.stdout, result.returncode


def run_shell_alias(command):
    """
    Execute the given system command.
    :param command: Command string to execute
    :return: (output, return_code)
    """
    result = subprocess.run(['bash', '-i', '-c', command], capture_output=True, text=True)
    return result.stdout, result.returncode


def process_txt(input_path, output_path, top_num):
    # Read all lines
    with open(input_path, 'r', encoding='utf-8') as f:
        lines = [line.strip() for line in f if line.strip()]

    # Count id occurrences and record the first line for each id
    id_count = collections.Counter()
    id_first_line = {}
    for line in lines:
        cols = line.split()
        if len(cols) < 5:
            continue
        id_ = cols[1]
        id_count[id_] += 1
        if id_ not in id_first_line:
            id_first_line[id_] = line

    # Sort ids by occurrence count in descending order
    sorted_ids = sorted(id_count.items(), key=lambda x: x[1], reverse=True)

    # Get top_num
    result_lines = []
    for id_, count in sorted_ids[:top_num]:
        first_line = id_first_line[id_]
        result_lines.append(f"{first_line} {count}")

    # Write to new file
    with open(output_path, 'w', encoding='utf-8') as f:
        for line in result_lines:
            f.write(line + '\n')

